#pragma once

#include<iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

enum{
    SockErr = 2,
    BindErr,
    ListenErr,
};

const int backlog = 10;

class Sock
{
public:
    Sock()
        :_sockfd(-1)
    {}
    ~Sock()
    {}

    void Socket()
    {
        _sockfd = socket(AF_INET,SOCK_STREAM,0);
        if(_sockfd < 0)
        {
            std::cerr << "create socket failed " << std::endl;
            exit(SockErr);
        }
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        socklen_t len = sizeof(local);
        if(bind(_sockfd,(const struct sockaddr*)&local,len))
        {
            std::cerr << "bind failed " << std::endl;
            exit(BindErr);
        } 
    }

    void Listen()
    {
        if(listen(_sockfd,backlog) < 0)
        {
            std::cerr << "listen failed " << std::endl;
            exit(ListenErr);
        }
    }

    int Accept(uint16_t* clientport,std::string* clientip)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int newfd = accept(_sockfd,(struct sockaddr*)&client,&len);
        if(newfd < 0)
        {
            std::cerr<< "accept failed"<< std::endl;
            return -1;
        }
        char ip_str[64];
        inet_ntop(AF_INET,&client.sin_addr,ip_str,sizeof(ip_str));
        *clientport = ntohs(client.sin_port);
        *clientip = ip_str;

        return newfd;
    }

    bool Connect(uint16_t serverport,std::string& serverip)
    {
        struct sockaddr_in server;
        memset(&server,0,sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        server.sin_addr.s_addr = inet_addr(serverip.c_str());

        socklen_t len = sizeof(server);
        if(connect(_sockfd,(const struct sockaddr*)&server,len) < 0 )
        {
            return false;
        }
        return true;
    }

    void Close()
    {
        close(_sockfd);
    }

    int Fd()
    {
        return _sockfd;
    }

private:
    int _sockfd;
};